<script setup>
import { forEach } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks';
import { useWatch } from '@/hooks/useWatch';
import { useDownload } from '@/hooks/tool.js';
import { getByDateEnergyResult } from '@/api/index.js';
import AreaForm from '@/views/components/AreaForm.vue';
import DateChart from '@/views/components/DateChart.vue';
import { TableList } from '@/components/MainComponents.js';
const typeList = {
  ELECTRICITY: '电',
  WATER: '水',
  AIR: '气',
  WARM: '暖',
};

const props = defineProps({
  type: { type: String, default: '' },
  unit: { type: String, default: '' },
});
const { type, unit } = toRefs(props);
const activeName = ref('quantity');
const chartRef = ref(null);
const tableData = ref(null);
const formParams = ref({});
const chartOpts = ref({
  color: ['#4992ff', '#5afe5d', '#eda422'],
  yAxis: [{ name: `单位：${unit.value}` }],
  series: Array.from({ length: 3 }, (_, idx) => {
    return {
      type: 'line',
      smooth: true,
      showSymbol: false,
      yAxisIndex: 0,
      itemStyle: {
        normal: {
          lineStyle: {
            type: idx === 0 ? 'dotted' : 'solid', //'dotted'点型虚线 'solid'实线 'dashed'线性虚线
          },
        },
      },
    };
  }),
  dataset: {
    dimensions: [
      'energyValueDate',
      { name: 'energyBasisValue', displayName: '能耗基准' },
      { name: 'energyConsumeValue', displayName: '实际能耗' },
      { name: 'energyConservationValue', displayName: '节能量' },
    ],
    source: [],
  },
});
const pageObj = ref({
  pageNum: 1,
  pageSize: 10,
});
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'energyValueDate',
      label: '统计时间',
    },
    {
      text: true,
      prop: 'type',
      label: '能源名称',
    },
    {
      text: true,
      prop: 'energyConsumeValue',
      label: `实际能耗量（${unit.value}）`,
    },
    {
      text: true,
      prop: 'energyBasisValue',
      label: `能耗基准（${unit.value}）`,
    },
    {
      text: true,
      prop: 'energyConservationValue',
      label: `节能量（${unit.value}）`,
    },
    {
      text: true,
      prop: 'energyConsumeCost',
      label: '实际能耗费用（元）',
    },
    {
      text: true,
      prop: 'energyBasisCost',
      label: '能耗基准费用（元）',
    },
    {
      text: true,
      prop: 'energyConservationCost',
      label: '节能收益（元）',
    },
  ],
});
const [res, loading, run] = useRequest(getByDateEnergyResult, {
  defaultParams: [],
  manual: true,
  onSuccess: res => {
    chartOpts.value.dataset.source = res.data ?? [];
    tableData.value = res.data.slice(0, 10) ?? [];
    forEach(tableData.value, n => {
      n.type = typeList[type.value];
    });
    pageObj.value = {
      pageNum: 1,
      pageSize: 10,
    };
  },
});
const handleQuery = queryParams => {
  formParams.value = queryParams.buildingCode;
  const params = {
    belong: '1',
    enterpriseCode: queryParams.buildingCode.enterpriseCode,
    projectCode: '',
    buildingCode: queryParams.buildingCode.buildingCode,
    energyType: type.value,
    dateType: chartRef.value?.dateParams.dateType,
    dateStart: chartRef.value?.dateParams.startTime,
    dateEnd: chartRef.value?.dateParams.endTime,
    projectType: 'TG',
    isUnit: true,
  };
  run(params);
};
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  tableData.value = res.value.slice((e.page - 1) * e.limit, e.page * e.limit);
  forEach(tableData.value, n => {
    n.type = typeList[type.value];
  });
};
const handleChart = dateParams => {
  if (dateParams.startTime && dateParams.endTime) {
    const params = {
      belong: '1',
      enterpriseCode: formParams.value.enterpriseCode,
      projectCode: '',
      buildingCode: formParams.value.buildingCode,
      energyType: type.value,
      dateType: dateParams.dateType,
      dateStart: dateParams.startTime,
      dateEnd: dateParams.endTime,
      projectType: 'TG',
      isUnit: true,
    };
    run(params);
  }
};
const handleExport = () => {
  const params = {
    belong: '1',
    enterpriseCode: formParams.value.enterpriseCode,
    projectCode: '',
    buildingCode: formParams.value.buildingCode,
    energyType: type.value,
    dateType: chartRef.value?.dateParams.dateType,
    dateStart: chartRef.value?.dateParams.startTime,
    dateEnd: chartRef.value?.dateParams.endTime,
    projectType: 'TG',
  };
  useDownload('/energyservice/overview/getByDateEnergyExcelResult', params, `${typeList[type.value]}能耗报表.xlsx`);
};
useWatch(activeName, n => {
  chartOpts.value.dataset.dimensions =
    n === 'quantity'
      ? [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '能耗基准' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConservationValue', displayName: '节能量' },
        ]
      : [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '费用基准' },
          { name: 'energyConsumeCost', displayName: '实际费用' },
          { name: 'energyConservationCost', displayName: '节能收益' },
        ];
  chartOpts.value.yAxis[0].name = n === 'quantity' ? `单位：${unit.value}` : '单位：元';
});
</script>
<template>
  <div>
    <el-tabs v-model="activeName" class="u-base-fg u-pl20" lazy>
      <el-tab-pane :label="typeList[type] + '能耗节能数据'" name="quantity"></el-tab-pane>
      <el-tab-pane label="节能收益数据" name="prices"></el-tab-pane>
    </el-tabs>
    <AreaForm ref="areaFormRef" projectType="TG" @handleQuery="handleQuery" style="margin-top: -20px" />
    <DateChart
      ref="chartRef"
      class="u-p20 u-base-fg"
      style="height: 360px"
      :extraOpts="chartOpts"
      @handleDateParams="handleChart"
    />
    <div class="contBox">
      <div class="u-df-ed mb20">
        <el-button type="primary" plain size="small" @click="handleExport">导出报表</el-button>
      </div>
      <TableList
        v-loading="loading"
        :total="res?.length ?? 0"
        :height="500"
        :tableData="tableData"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.u-pl20 {
  padding-left: 20px;
}
.u-pb20 {
  padding-bottom: 20px;
}
</style>
